package com.wechat.config;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.swak.boot.ApplicationBooter;
import com.swak.persistence.DatabaseStorage;
import com.swak.utils.IOUtils;
import com.swak.utils.StringUtils;
import com.wechat.service.InitializeService;

/**
 * 数据初始化
 * 
 * @author 618lf
 */
@Component
public class InitializeConfig extends DatabaseStorage implements ApplicationBooter {

	private InitializeService initializeService;

	public InitializeConfig(DataSource dataSource, InitializeService initializeService) {
		super(dataSource);
		this.initializeService = initializeService;
	}

	public void afterPropertiesSet() throws Exception {

		// 初始化脚本
		this.initScript();

		// 初始化用户
		this.initSubject();
	}

	private void initScript() {
		String tables = IOUtils.readAsText(this.getClass(), "script.sql");
		String[] sqls = StringUtils.split(tables, ";");
		for (String sql : sqls) {
			this.executeUpdate(sql);
		}
	}

	private void initSubject() {
		this.initializeService.doInitialize();
	}

	// 不需要输出信息

	@Override
	protected void error(Throwable e) {
	}

	@Override
	protected void error(String format, String sql, Throwable e) {
	}

	// 系统启动
	@Override
	public void onApplicationEvent(ApplicationContext context) {

		// 初始化脚本
		this.initScript();

		// 初始化用户
		this.initSubject();
	}
}